package com.androidx.paging.datasource

import androidx.paging.PositionalDataSource
import com.androidx.paging.model.GoodsModel

/**
 * Created by zhangyuncai on 2020/8/6.
 * PositionalDataSource：按位置加载，如加载指定从第n条到n+20条
 */
class GoodsPositionalDataSource : PositionalDataSource<GoodsModel>() {
    /**
     * 分页加载
     */
    override fun loadRange(params: LoadRangeParams, callback: LoadRangeCallback<GoodsModel>) {
        val datas = setDatas(params.startPosition, params.loadSize)
        callback.onResult(datas)
    }

    /**
     *  //初次加载
     */
    override fun loadInitial(params: LoadInitialParams, callback: LoadInitialCallback<GoodsModel>) {
        val datas = setDatas(0, params.pageSize)
        callback.onResult(datas, 0)
    }

    private fun setDatas(start: Int, size: Int): List<GoodsModel> {
        val datas = mutableListOf<GoodsModel>()
        for (index in start until size + start) {
            datas.add(GoodsModel().apply {
                id = index
                name = "商品名:${index}"
            })
        }
        return datas
    }
}